package vn.bang.utility;

import java.net.DatagramSocket;
import java.net.SocketException;

public class SocketUtil {

	static public DatagramSocket getDatagramSocket(int minPort, int maxPort) {
		if (minPort > maxPort) {
			throw new IllegalArgumentException(
					String.format(
							"Invalid parameters, minPort(%d) must be smaller than maxPort(%d).",
							minPort, maxPort));
		}

		DatagramSocket datagramSocket = null;
		int port = minPort;
		do {
			datagramSocket = getSocketAvailable(port);
			port++;
		} while (null == datagramSocket && port <= maxPort);
		
		return datagramSocket;
	}

	static public DatagramSocket getSocketAvailable(int port) {
		boolean available = Boolean.TRUE;
		DatagramSocket datagramSocket = null;
		try {
			datagramSocket = new DatagramSocket(port);
		} catch (SocketException e) {
			available = Boolean.FALSE;
		}

		if (available) {
			return datagramSocket;
		}

		return null;
	}
	
	static public boolean isPortAvailable(int port) {
		boolean available = Boolean.TRUE;
		DatagramSocket datagramSocket = null;
		try {
			datagramSocket = new DatagramSocket(port);
		} catch (SocketException e) {
			available = Boolean.FALSE;
		}

		if (available) {
			if (null != datagramSocket && !datagramSocket.isClosed()) {
				datagramSocket.close();
			}
		}

		return available;
	}

}
